/*
 * @lc app=leetcode.cn id=1011 lang=typescript
 *
 * [1011] 在 D 天内送达包裹的能力
 */

// @lc code=start
function shipWithinDays(weights: number[], D: number): number {
  let left = Math.max(...weights);
  let right = weights.reduce((prev, curr) => prev + curr);

  while (left < right) {
    const mid = ((right - left) >> 1) + left;
    let needDays = 1;
    let count = 0;
    // 计算当前x需要几天可以运输完毕
    for (let w of weights) {
      if (count + w > mid) {
        needDays++;
        count = 0;
      }
      count += w;
    }

    if (needDays <= D) {
      right = mid;
    } else {
      left = mid + 1;
    }
  }

  return left;
}
// @lc code=end
